import { defineStore } from 'pinia'

export const useLegalTokenStore = defineStore(
  'legalToken',
  () => {
    const token = ref('')
    const expiresIn = ref(0)

    const setLegalToken = (t: string, expires: number) => {
      token.value = t
      expiresIn.value = Date.now() + expires * 1000

      uni.setStorageSync('legal_access_token', t)
      uni.setStorageSync('legal_access_expire', expiresIn.value)
    }

    const loadFromStorage = () => {
      token.value = uni.getStorageSync('legal_access_token') || ''
      expiresIn.value = uni.getStorageSync('legal_access_expire') || 0
    }
    loadFromStorage()

    const isExpired = computed(() => {
      if (!token.value)
        return true
      return Date.now() >= expiresIn.value
    })

    const getValidToken = () => {
      return isExpired.value ? '' : token.value
    }
    /** 清理 token */
    const logout = () => {
      token.value = ''
      expiresIn.value = 0
      uni.removeStorageSync('legal_access_token')
      uni.removeStorageSync('legal_access_expire')
    }
    return {
      token,
      isExpired,
      getValidToken,
      setLegalToken,
      logout,
    }
  },
  { persist: true },
)
